/**
 *
 */
package anysware.gwt.client.ui;

import anysware.gwt.client.ApplicationEvent;
import anysware.gwt.client.ApplicationListener;
import anysware.gwt.client.EventConstants;
import anysware.gwt.client.rest.CallbackEvent;
import anysware.gwt.client.rest.CallbackListener;
import anysware.gwt.client.rest.RestRequestBuilder;
import anysware.gwt.client.util.PageUtils;
import anysware.gwt.client.util.QueryBuilder;

import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.History;

/**
 * TODO: doc me
 *
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 103 $
 * @version
 */
public class SearchController implements ApplicationListener, CallbackListener {
	private final AnyswareApplicationFrame	mainFrame;

	public SearchController(
	        final AnyswareApplicationFrame anyswareApplicationFrame) {
		mainFrame = anyswareApplicationFrame;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see anysware.gwt.client.ApplicationListener#fireEvent(anysware.gwt.client.ApplicationEvent)
	 */
	public void fireEvent(final ApplicationEvent event) {
		if (event.getEventType() == EventConstants.SEARCH_EVENT) {
			History.newItem("/search?q=" + event.getData());
		}
		final String endPointUrl = PageUtils.getProperty("endpoint.search")
		        + "?"
		        + new QueryBuilder().add("q", (String) event.getData()).build();
		final RestRequestBuilder builder = RestRequestBuilder.createBuilder(
		        "GET", endPointUrl);
		builder.sendRequest(null, this);
	}

	public void handle(final CallbackEvent event) {
		if (event.getReason() == CallbackEvent.Reason.SUCCESS) {
			final Response response = event.getResponse();
			if (response.getStatusCode() == 200) {
				mainFrame.getWorkspace().setListView(
				        new SearchResultList(JSONParser.parse(
				                response.getText()).isObject()));
			}
		}
	}
}
